package io.atom.modules.security.oauth2;

import io.atom.common.constant.JwtClaimsConstant;
import io.atom.common.context.BaseContext;
import io.atom.common.exception.ErrorCode;
import io.atom.common.properties.JwtProperties;
import io.atom.common.utils.ConvertUtils;
import io.atom.common.utils.JwtUtil;
import io.atom.common.utils.MessageUtils;
import io.atom.modules.security.service.ShiroService;
import io.atom.modules.security.user.UserDetail;
import io.atom.modules.sys.entity.SysUserEntity;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * 认证
 *
 */
@Component
@AllArgsConstructor
public class Oauth2Realm extends AuthorizingRealm {
    private final ShiroService shiroService;

    private JwtProperties jwtProperties;

    /**
     * 只限定这个realm只能处理JwtToken
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Oauth2Token;
    }

    /**
     * 身份认证/登录
     * 授权
     * leon.luo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //接收头部token
        String accessToken = (String) token.getPrincipal();

        //jwt解密
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), accessToken);

        //类型转换
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());

        BaseContext.setCurrentId(userId);

        //根据userId，查询用户信息
        SysUserEntity userEntity = shiroService.getUser(userId);

        //转换成UserDetail对象
        UserDetail userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class);

        //获取用户对应的部门数据权限
        List<Long> deptIdList = shiroService.getDataScopeList(userDetail.getId());
        userDetail.setDeptIdList(deptIdList);

        //账号锁定
        if (userDetail.getStatus() == 0) {
            throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK));
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName());
        return info;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDetail user = (UserDetail) principals.getPrimaryPrincipal();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(user);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

}